package com.shuoyue.ycgk.ui.news;

import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.shuoyue.ycgk.Constant;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.appcatch.FileUtil;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.base.ListWithPage;
import com.shuoyue.ycgk.entity.News;
import com.shuoyue.ycgk.entity.NewsType;
import com.shuoyue.ycgk.entity.NoticeFile;
import com.shuoyue.ycgk.ui.common.download.DownloadContract;
import com.shuoyue.ycgk.ui.news.contract.NewsContract;
import com.shuoyue.ycgk.utils.NOpenFiles;
import com.shuoyue.ycgk.utils.ShareUtil;
import com.shuoyue.ycgk.views.ResizableImageView;
import com.zzhoujay.richtext.RichText;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NewsInfoWebActivity extends BaseMvpActivity<NewsContract.Presenter> implements NewsContract.View, DownloadContract.View {


    @BindView(R.id.page_title)
    TextView pageTitle;
    @BindView(R.id.img)
    ResizableImageView img;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.tag)
    TextView tag;
    @BindView(R.id.content)
    WebView content;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.filename)
    RecyclerView filename;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.scorllView)
    NestedScrollView scorllView;
    NoticeFileAdapter mAdapter;
    DownloadContract.Presenter downloadPresenter;

    News newsInfo;
    int id;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_news_info_web;
    }

    @Override
    protected void initView() {
        pageTitle.setText("详情");
        ivRight.setVisibility(View.VISIBLE);
        ivRight.setImageResource(R.mipmap.share);
        mAdapter = new NoticeFileAdapter(new ArrayList());
        filename.setAdapter(mAdapter);
        filename.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            NoticeFile noticeFile = mAdapter.getItem(position);
            switch (view.getId()) {
                case R.id.tv_title:
                    File file = new File(FileUtil.getPath(mContext) + "/资讯/", noticeFile.getAttachmentName());
                    if (file.exists()) {
                        NOpenFiles.openFile(NewsInfoWebActivity.this, file);
                    } else {
                        downloadPresenter.downloadFile(noticeFile.getAttachmentUrl(),
                                new File(FileUtil.getPath(mContext) + "/资讯/", noticeFile.getAttachmentName()).getAbsolutePath());
                    }
                    break;
            }
        });
        registScrollToTop(scorllView);
        initWebView(content);
    }


    @Override
    public void initData() {
        mPresenter = new NewsContract.Presenter();
        mPresenter.attachView(this);
        downloadPresenter = new DownloadContract.Presenter();
        downloadPresenter.attachView(this);
        id = getIntent().getIntExtra("id", 0);
        mPresenter.getNewsInfo(id);
    }


    @Override
    public void setNewsInfo(News newsInfo) {
        this.newsInfo = newsInfo;

        if (TextUtils.isEmpty(newsInfo.getCoverUrl())) {
            img.setVisibility(View.GONE);
        } else {
            Glide.with(mContext).load(newsInfo.getCoverUrl()).error(R.mipmap.img_loading_gray).into(img);
        }
        title.setText(newsInfo.getTitle());
        time.setText(newsInfo.getUpdateTime());
        tag.setVisibility(newsInfo.getBrowseNum() > 1000 ? View.VISIBLE : View.GONE);
        content.loadData(newsInfo.getContent(), "text/html", "UTF-8");
//        content.loadUrl(Constant.HOST_INTERFACE+"/api/share/information.html?id="+id);
        if (newsInfo.getAttachmentList() != null && newsInfo.getAttachmentList().size() > 0) {
            mAdapter.resetData(newsInfo.getAttachmentList());
        }

    }

    public void initWebView(WebView mWebView) {
        //webView 设置属性
        mWebView.clearCache(true);
//        mWebView.addJavascriptInterface(this, "fhy");
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setTextZoom(250);
        mWebView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {

            }

        });
        WebViewClient wvc = new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                new Handler().postDelayed(() -> getWebContentHeight(), 1000);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("用户单击超连接", url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        };
        mWebView.setWebViewClient(wvc);
    }

    @Override
    public void setNewsList(ListWithPage<News> newsList) {

    }

    @Override
    public void setNewsTypeList(List<NewsType> newsTypeList) {

    }

    @Override
    protected void onDestroy() {
        RichText.clear(this);
        super.onDestroy();

    }


    @OnClick({R.id.back, R.id.iv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.iv_right:
                if (newsInfo != null)
                    ShareUtil.shareUrl(this, ShareUtil.NEWS_URL + id,
                            newsInfo.getTitle(),
                            "",
                            null);
                break;
        }
    }


    @Override
    public void downloadSuc(File file) {
        NOpenFiles.openFile(this, file);
    }

    @Override
    public void progress(int progress) {

    }

    @Override
    public void downloadStart() {

    }

    @Override
    public void downloadError(String msg) {

    }

    private void getWebContentHeight() {
        if (content != null)
            content.post(() -> {
                content.measure(0, 0);
                int measureHeight = content.getMeasuredHeight();
                ViewGroup.LayoutParams layoutParams = content.getLayoutParams();
                layoutParams.height = measureHeight + 100;
                content.setLayoutParams(layoutParams);
            });
    }

    @Override
    public void onBackPressed() {
        back();
    }

    void back() {
        if (content.canGoBack()) {
            content.goBack();
        } else {
            finish();
        }
    }
}
